import {
  DeleteOutlined,
  EditOutlined,
  PlusOutlined,
  SettingOutlined,
} from '@ant-design/icons';
import {
  type ActionType,
  PageContainer,
  type ProColumns,
  ProTable,
} from '@ant-design/pro-components';
import { Button, Form, Input, Modal, message, Select, Tag, Tree } from 'antd';
import { useEffect, useRef, useState } from 'react';
import {
  createRole,
  deleteRole,
  getPermissionTree,
  getRoles,
  updateRole,
} from '@/services/ant-design-pro/rbac';

const Roles: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [permissionTree, setPermissionTree] = useState<API.Permission[]>([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [permissionModalVisible, setPermissionModalVisible] = useState(false);
  const [editingRole, setEditingRole] = useState<API.Role | null>(null);
  const [selectedRole, setSelectedRole] = useState<API.Role | null>(null);
  const [form] = Form.useForm();
  const [selectedPermissions, setSelectedPermissions] = useState<string[]>([]);

  useEffect(() => {
    loadPermissionTree();
  }, []);

  const loadPermissionTree = async () => {
    try {
      const response = await getPermissionTree();
      setPermissionTree(response.data || []);
    } catch (_error) {
      message.error('加载权限树失败');
    }
  };

  const handleCreate = () => {
    setEditingRole(null);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEdit = (record: API.Role) => {
    setEditingRole(record);
    form.setFieldsValue(record);
    setModalVisible(true);
  };

  const handleDelete = async (id: string) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个角色吗？',
      onOk: async () => {
        try {
          await deleteRole(id);
          message.success('删除成功');
          actionRef.current?.reload();
        } catch (_error) {
          message.error('删除失败');
        }
      },
    });
  };

  const handleSubmit = async (values: any) => {
    try {
      if (editingRole?.id) {
        await updateRole({
          id: editingRole.id,
          ...values,
        });
        message.success('更新成功');
      } else {
        await createRole(values);
        message.success('创建成功');
      }
      setModalVisible(false);
      actionRef.current?.reload();
    } catch (_error) {
      message.error('操作失败');
    }
  };

  const handlePermissionConfig = async (record: API.Role) => {
    setSelectedRole(record);
    setSelectedPermissions(record.permissions?.map((p) => p.id || '') || []);
    setPermissionModalVisible(true);
  };

  const handlePermissionSubmit = async () => {
    if (!selectedRole?.id) return;

    try {
      await updateRole({
        id: selectedRole.id,
        permissionIds: selectedPermissions,
      });
      message.success('权限配置成功');
      setPermissionModalVisible(false);
      actionRef.current?.reload();
    } catch (_error) {
      message.error('权限配置失败');
    }
  };

  const renderPermissionTree = (permissions: API.Permission[]): any[] => {
    return permissions.map((permission) => {
      if (permission.children && permission.children.length > 0) {
        return {
          title: permission.name,
          key: permission.id,
          children: renderPermissionTree(permission.children),
        };
      }
      return {
        title: permission.name,
        key: permission.id,
      };
    });
  };

  const onCheck = (checkedKeys: any) => {
    setSelectedPermissions(checkedKeys);
  };

  const renderStatus = (status: any) => (
    <Tag color={status === 'active' ? 'green' : 'red'}>
      {status === 'active' ? '启用' : '禁用'}
    </Tag>
  );

  const renderPermissionCount = (permissions?: API.Permission[]) =>
    permissions?.length || 0;

  const columns: ProColumns<API.Role>[] = [
    {
      title: '角色名称',
      dataIndex: 'name',
      key: 'name',
      width: 150,
    },
    {
      title: '角色编码',
      dataIndex: 'code',
      key: 'code',
      width: 200,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: renderStatus,
    },
    {
      title: '权限数量',
      dataIndex: 'permissions',
      key: 'permissions',
      width: 120,
      render: renderPermissionCount,
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 180,
      valueType: 'dateTime',
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      width: 200,
      render: (text, record, _, action) => [
        <Button
          key="edit"
          type="link"
          size="small"
          icon={<EditOutlined />}
          onClick={() => handleEdit(record)}
        >
          编辑
        </Button>,
        <Button
          key="permission"
          type="link"
          size="small"
          icon={<SettingOutlined />}
          onClick={() => handlePermissionConfig(record)}
        >
          权限
        </Button>,
        <Button
          key="delete"
          type="link"
          size="small"
          danger
          icon={<DeleteOutlined />}
          onClick={() => handleDelete(record.id || '')}
        >
          删除
        </Button>,
      ],
    },
  ];

  return (
    <PageContainer
      header={{
        title: '角色管理',
        breadcrumb: {
          items: [
            {
              title: '系统管理',
            },
            {
              title: '角色管理',
            },
          ],
        },
      }}
    >
      <ProTable<API.Role>
        columns={columns}
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        request={async (params: any) => {
          const response = await getRoles({
            current: params.current,
            pageSize: params.pageSize,
            name: params.name,
            status: params.status,
          });
          return {
            data: response.data || [],
            success: response.success,
            total: response.total,
          };
        }}
        columnsState={{
          persistenceKey: 'roles-table',
          persistenceType: 'localStorage',
        }}
        rowSelection={{}}
        tableAlertRender={false}
        toolBarRender={() => [
          <Button
            key="create"
            type="primary"
            onClick={handleCreate}
            icon={<PlusOutlined />}
          >
            新建角色
          </Button>,
        ]}
      />

      {/* 创建/编辑角色弹窗 */}
      <Modal
        title={editingRole ? '编辑角色' : '新建角色'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        onOk={() => form.submit()}
        width={600}
      >
        <Form form={form} layout="vertical" onFinish={handleSubmit}>
          <Form.Item
            name="name"
            label="角色名称"
            rules={[{ required: true, message: '请输入角色名称' }]}
          >
            <Input placeholder="请输入角色名称" />
          </Form.Item>

          <Form.Item
            name="code"
            label="角色编码"
            rules={[{ required: true, message: '请输入角色编码' }]}
          >
            <Input placeholder="请输入角色编码" />
          </Form.Item>

          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select placeholder="请选择状态">
              <Select.Option value="active">启用</Select.Option>
              <Select.Option value="inactive">禁用</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item name="description" label="描述">
            <Input.TextArea rows={3} placeholder="请输入角色描述" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 权限配置弹窗 */}
      <Modal
        title={`配置角色权限 - ${selectedRole?.name}`}
        open={permissionModalVisible}
        onCancel={() => setPermissionModalVisible(false)}
        onOk={handlePermissionSubmit}
        width={600}
      >
        <div style={{ marginBottom: 16 }}>
          <p>请为角色 "{selectedRole?.name}" 配置权限：</p>
        </div>
        <Tree
          checkable
          checkedKeys={selectedPermissions}
          onCheck={onCheck}
          treeData={renderPermissionTree(permissionTree)}
          height={400}
        />
      </Modal>
    </PageContainer>
  );
};

export default Roles;
